package com.mumulx.check.web.config.security.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mumulx.check.service.service.UserInfoService;
import com.mumulx.check.service.util.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/10/25
 *  Time: 20:59
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Value("${spring.security.loginType}")
    private String loginType;//配置中的security.loginType
    //进行对象转换，可以将对象转换为json，也可以将json转换为对象
    private static ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    UserInfoService userInfoService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response,Authentication authentication)throws ServletException, IOException {

        if(loginType.equalsIgnoreCase("JSON")){
            /*UserInfo userInfoByDerails = (UserInfo) authentication.getPrincipal();

            UserInfo userInfo = userInfoService.getUserInfoByUserTel(userInfoByDerails.getUsername());

            request.getSession().setAttribute("user_name",userInfo.getUserName());
            request.getSession().setAttribute("user_id",userInfo.getUserId());
            request.getSession().setAttribute("user_tel",userInfo.getUserTel());*/
            //先设置编码再获取流
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(objectMapper.writeValueAsString(
                   RespBean.ok("登录成功！")
            ));
            out.flush();
            out.close();
            //log.info("登录成功======================================"+userInfo.getUserTel());
            log.info("登录成功======================================");

        }else{
            //跳转到登陆之前请求的页面
            log.info("跳转到登陆之前请求的页面======================================");

            super.onAuthenticationSuccess(request,response,authentication);
        }
    }


}
